package br.com.sovi.gwt.client.cercaeletronica;

import java.util.List;

import br.com.sovi.gwt.client.PontoUtils;
import br.com.sovi.gwt.client.entity.Ponto;
import br.com.sovi.gwt.client.entity.cerca.Cerca;

import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.LargeMapControl3D;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.layout.FitLayout;

public class CercaCentralPanel extends Panel implements CercaHandler {

	private MapWidget map;

	private CercaMapClickHandler handler;

	public CercaCentralPanel() {
		this.setLayout(new FitLayout());

		map = new MapWidget();
		map.setSize("100%", "100%");
		map.addControl(new LargeMapControl3D());

		handler = new CercaMapClickHandler(map);
		map.addMapClickHandler(handler);

		new Timer() {
			@Override
			public void run() {
				map.checkResizeAndCenter();
			}
		}.schedule(1);

		this.add(map);
		this.doLayout();
	}

	@Override
	public List<Ponto> getPoints() {
		return handler.getPoints();
	}

	@Override
	public void showCerca(Cerca cerca) {
		List<Ponto> pontos = cerca.getPoints();

		if (pontos == null || pontos.isEmpty()) {
			Window.alert("Este dispositivo não possuí cerca.");
		}

		LatLng[] lls = new LatLng[pontos.size()];

		for (int i = 0; i < pontos.size(); i++) {
			lls[i] = PontoUtils.toLatLng(pontos.get(i));
		}

		for (LatLng latLng : lls) {
			GWT.log("Localização: " + latLng, null);
		}
		
		handler.setPolygon(lls);
	}

	@Override
	public void clearCerca() {
		handler.clear();
	}

}
